#include <iostream>
#include <memory>

class MyClass
{
public:
    void printMessage() const
    {
        std::cout << "Hello from MyClass!" << std::endl;
    }
};

int main()
{
    // 创建一个由 shared_ptr 管理的 MyClass 对象
    std::shared_ptr<MyClass> sharedObject = std::make_shared<MyClass>();

    // 通过 shared_ptr 构造一个 weak_ptr
    std::weak_ptr<MyClass> weakRef(sharedObject);

    // 检查 weak_ptr 是否已过期
    if (weakRef.expired())
    {
        std::cout << "weak_ptr is already expired." << std::endl;
    }
    else
    {
        std::cout << "weak_ptr is NOT expired." << std::endl;

        // 使用 lock() 获取一个临时的 shared_ptr
        std::shared_ptr<MyClass> lockedObject = weakRef.lock();
        if (lockedObject)
        {
            // 如果 lock() 返回非空 shared_ptr，说明对象仍然存在，可以安全地使用
            lockedObject->printMessage();
            std::cout << "use_count:"<<weakRef.use_count() << std::endl;
        }
        else
        {
            std::cout << "The object has been deleted since the weak_ptr was created." << std::endl;
        }
    }

    // 删除 shared_ptr，导致 MyClass 对象被销毁
    sharedObject.reset();

    // 再次检查 weak_ptr 是否已过期
    if (weakRef.expired())
    {
        std::cout << "After deleting the shared_ptr, the weak_ptr is now expired." << std::endl;
    }
    else
    {
        std::cout << "After deleting the shared_ptr, the weak_ptr is NOT expired (this should not happen)." << std::endl;
    }

    return 0;
}